//
//  BDHomeViewController.m
//  BadBoy
//
//  Created by wen on 2017/3/10.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDHomeViewController.h"
#import "BDHomeTableViewCell.h"
#import "BDPublishViewController.h"
#import "BDHomeDetailViewController.h"
#import "BDHomeCellBottomView.h"
#import "BDUserModel.h"
#import "BDCityInfo.h"
#import "JFCityViewController.h"
#import "BDForwardViewController.h"
#import "BDHomeSearchViewController.h"
#import "UIButton+WebCache.h"
#import "PBViewController.h"
#import "BDLocationServer.h"
#import "SDCycleScrollView.h"
#import "BDVipPayView.h"
#import <UMSocialCore/UMSocialCore.h>
#import <UShareUI/UShareUI.h>
#import "AppDelegate.h"
#import "CameraPhotoBehavior.h"
#import "BDVIPViewController.h"
#import "BDButtonAlert.h"
#import "BDUserInfoViewController.h"
#import "BDPayViewController.h"
#import "BDMallProductModel.h"
#import "BDPostModel.h"
#import "BDShopInfoDeatilViewController.h"

#import "BDPostListViewController.h"

@interface BDHomeViewController ()<UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate, PBViewControllerDelegate, PBViewControllerDataSource, SDCycleScrollViewDelegate>
{
    NSInteger currentSelectedIndex;
    NSIndexPath *exchangeIndexPath;
    NSArray *showImagesArray;
    UIView *curClickView;
    BOOL notFirst;
    BOOL isChangeSegementRequest;
    BOOL isFirst;
    NSArray *bannerInfos;
}

@property (nonatomic, strong) UIButton *cityButton;
@property (nonatomic, strong) UIButton *rightButton;
@property (nonatomic, strong) UIButton *searchButton;
@property (nonatomic, strong) SDCycleScrollView *lunboView;
@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *datasource;
@property (nonatomic, strong) NSMutableDictionary *dictionary;
@property (nonatomic, strong) NSMutableArray *startPageArray;
@property (nonatomic, strong) UIActivityIndicatorView *indicatorView;
@property (nonatomic, strong) BDButtonAlert *buttonAlert;
@property (nonatomic, strong) NSString *typeString;
@property (nonatomic, copy) void(^changeTitleBlock)(NSString *newTitleString);
@property (nonatomic, strong) UIButton *titleButton;

@end

@implementation BDHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSUserDefaults standardUserDefaults] setObject:ASLocalizedString(@"全部")forKey:@"shopAndPostType"];
    self.typeString = ASLocalizedString(@"全部");
    
    [self layoutViews];
    [self bindRAC];
    

    __weak BDHomeViewController *weakSelf = self;
    self.changeTitleBlock = ^(NSString *newTitleString) {
        weakSelf.typeString = newTitleString;
        [[NSUserDefaults standardUserDefaults] setObject:weakSelf.typeString forKey:@"shopAndPostType"];
        [weakSelf.titleButton setTitle:weakSelf.typeString forState:UIControlStateNormal];
        [weakSelf.titleButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -12, 0, 12)];
        [weakSelf.titleButton setImageEdgeInsets:UIEdgeInsetsMake(0, [weakSelf.typeString widthWithFont:weakSelf.titleButton.titleLabel.font] + 2, 0, - ([weakSelf.typeString widthWithFont:weakSelf.titleButton.titleLabel.font] + 2))];
        isChangeSegementRequest = YES;
        [weakSelf.dictionary removeAllObjects];
        [weakSelf.datasource removeAllObjects];
        weakSelf.startPageArray = @[@"1",@"1",@"1",@"1"].mutableCopy;
        [weakSelf.tableView reloadData];
        [weakSelf requestDatasource];
    };
    
    
    self.startPageArray = @[@"1",@"1",@"1",@"1"].mutableCopy;
    self.dictionary = [NSMutableDictionary dictionary];
    self.datasource = @[].mutableCopy;
    
    [BDUserModel getUserIfOverdueAfterBlock:^{
        [self afterHaveUser];
    }];
    
//    BDUserModel *user = [BDUserModel getCurrentUser];
//
//    if (user.is_guest == YES || user == nil) {
//        [MBManager showLoadingAlert:ASLocalizedString(@"正在加载")clickHidden:NO clickBlock:nil];
//        NSString *url = [NSString stringWithFormat:@"%@guest", KBDBaseURL];
//        NSDictionary *para = @{@"guest_id":[[[UIDevice currentDevice] identifierForVendor] UUIDString]};
//        RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:para validation:nil automaticProcessingError:YES] execute:nil];
//        [signal subscribeNext:^(id  _Nullable x) {
//            [MBManager hideAlert];
//            BDUserModel *newUser = [BDUserModel mj_objectWithKeyValues:x];
//            newUser.unique_id = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
//            [newUser saveCurrentUser];
//            [newUser saveTouristsUser];
//            [self afterHaveUser];
//        }];
//
//        [signal subscribeError:^(NSError * _Nullable error) {
//            [MBManager hideAlert];
//            [self showErrorViewWithTapBlock:^{
//
//            }];
//        }];
//    }else{
//        [self afterHaveUser];
//    }
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if (self.buttonAlert != nil) {
        [self.buttonAlert removeFromSuperview];
        self.buttonAlert = nil;
    }
}

- (void)afterHaveUser{
    BDUserModel *currentUser = [BDUserModel getCurrentUser];
    self.userGuest = [NSString stringWithFormat:@"%@", @(currentUser.is_guest)];
    [self requestDatasource];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.topView];
    self.tableView.hidden = YES;
    [self.indicatorView startAnimating];
    [self refreshNaviInfo];
}

//首页需要更新数据的部分是
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self loginSuccessRefresh];
    NSString *newTypeString = [[NSUserDefaults standardUserDefaults] objectForKey:@"shopAndPostType"];
    if (![newTypeString isEqualToString:self.typeString]) {
        if (self.changeTitleBlock) {
            self.changeTitleBlock(newTypeString);
        }
    }
}

- (void)loginSuccessRefresh{
    if (isFirst == NO) {
        isFirst = YES;
    }else {
        BDUserModel *user = [BDUserModel getCurrentUser];
        if (user != nil) {
            BOOL flag = YES;
            if ([self.userGuest isNotEmpty]) {
                flag = user.is_guest != self.userGuest.integerValue;
            }
            if (user != nil && flag == YES) {
                [self refreshNaviInfo];
                [self.dictionary removeAllObjects];
                [self.datasource removeAllObjects];
                self.startPageArray = @[@"1",@"1",@"1",@"1"].mutableCopy;
                [self requestDatasource];
                self.userGuest = [NSString stringWithFormat:@"%@", @(user.is_guest)];
            }
        }
    }
}

- (void)refreshNaviInfo{
    //1.获取定位城市，如果没有打开定位，那么默认为广州，打开定位的情况下，如果该城市没有在开放城市列表，那么也默认为广州，如果是在开放城市列表，那么显示为开放城市列表；
    //2.在选择城市存在的情况下，如果当前定位城市不是选择城市的时候，如果定位城市是开发城市，那么提示跳转，否则不提示跳转（这里需要注意的一个点是：当前定位没有开放的时候默认广州不能理解为定位成功为广州）
    
    if (notFirst == NO) {
        notFirst = YES;
        NSString *lastCity = [[NSUserDefaults standardUserDefaults] objectForKey:@"lastCity"];
        
        
        BDLocationModel *locationModel = [BDLocationModel getLocationInfo];
        NSDictionary *agreeArray = [NSDictionary dictionaryWithContentsOfFile:[DocumentPath stringByAppendingPathComponent:@"sectionData.plist"]];
        BOOL haveAgreeCity = NO;
        for (NSArray *value in agreeArray.allValues) {
            if ([value containsObject:locationModel.city] && [BDLocationServer whetherOpenLocationServer]) {
                haveAgreeCity = YES;
                break;
            }
        }
        
        if (![lastCity isNotEmpty]) {
            if (haveAgreeCity == YES) {
                [self exChangeCityNameWithName:locationModel.city];
            }else{
                [self exChangeCityNameWithName:@"广州市"];
            }
        }else{
            [self requestBanner];
            if (![locationModel.city isEqualToString:lastCity] && haveAgreeCity == YES) {
                [self.view alertWithTitle:ASLocalizedString(@"提示")message:[NSString stringWithFormat:ASLocalizedString(@"当前定位在%@，是否切换？"), locationModel.city] type:AlertTypeAlert cancleTitle:ASLocalizedString(@"不切换")otherTitle:@[ASLocalizedString(@"好的")] clickBlock:^(NSInteger index) {
                    if (index == 1) {
                        [self exChangeCityNameWithName:locationModel.city];
                        [self.dictionary removeAllObjects];
                        [self.datasource removeAllObjects];
                        self.startPageArray = @[@"1",@"1",@"1",@"1"].mutableCopy;
                        [self.tableView reloadData];
                        [self requestDatasource];
                    }
                }];
            }
        }
    }
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"saveCityList" object:nil];
}

- (void)layoutViews{
    UIBarButtonItem *cityBarButton=[[UIBarButtonItem alloc]initWithCustomView:self.cityButton];
    self.navigationItem.leftBarButtonItem = cityBarButton;
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:self.rightButton];
    UIBarButtonItem *searchItem = [[UIBarButtonItem alloc]initWithCustomView:self.searchButton];
    self.navigationItem.rightBarButtonItems = @[rightItem, searchItem];
    
    self.titleButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _titleButton.size = CGSizeMake(80, 44);
    [_titleButton setTitle:self.typeString forState:UIControlStateNormal];
    [_titleButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _titleButton.titleLabel.font = [UIFont boldSystemFontOfSize:17];
    [_titleButton setImage:[UIImage imageNamed:@"shouye_sanjiao"] forState:UIControlStateNormal];
    [_titleButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -12, 0, 12)];
    [_titleButton setImageEdgeInsets:UIEdgeInsetsMake(0, [self.typeString widthWithFont:_titleButton.titleLabel.font] + 2, 0, - ([self.typeString widthWithFont:_titleButton.titleLabel.font] + 2))];
    [[_titleButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        if (self.buttonAlert != nil) {
            [self.buttonAlert hidden];
            self.buttonAlert = nil;
            return;
        }
        self.buttonAlert = [BDButtonAlert showInShouyeWithView:self.view buttonTitleArray:@[ASLocalizedString(@"全部"), ASLocalizedString(@"水疗"), @"KTV", ASLocalizedString(@"夜总会"), ASLocalizedString(@"酒吧"), ASLocalizedString(@"沐足"), ASLocalizedString(@"其他")] finishBlock:^(NSString *buttonTitle) {
            if (self.changeTitleBlock) {
                self.changeTitleBlock(buttonTitle);
            }
        }];
    }];
    
    self.navigationItem.titleView = _titleButton;
}

- (void)bindRAC{
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"exchangePost" object:nil] subscribeNext:^(NSNotification * _Nullable x) {
        [self.tableView reloadData];
    }];
    
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"vipChange" object:nil] subscribeNext:^(NSNotification * _Nullable x) {
        [self.tableView reloadData];
    }];
    
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"guanzhuChange" object:nil] subscribeNext:^(NSNotification * _Nullable x) {
        //清空关注列表帖子
        [self.dictionary setObject:[NSMutableArray array] forKey:@"3"];
        //重置关注请求数据页数
        [self.startPageArray setObject:@"1" atIndexedSubscript:3];
        //如果当前页面显示的就是关注，那么重新请求数据并刷新
        if (currentSelectedIndex == 3) {
            [self requestDatasource];
        }
    }];
    
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"blackListChange" object:nil] subscribeNext:^(NSNotification * _Nullable x) {
        if (self.navigationController.topViewController != self) {
            [self.navigationController popToViewController:self animated:YES];
        }
        [self.dictionary removeAllObjects];
        [self.datasource removeAllObjects];
        self.startPageArray = @[@"1",@"1",@"1",@"1"].mutableCopy;
        [self.tableView reloadData];
        [self requestDatasource];
    }];
    
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"deletedPost" object:nil] subscribeNext:^(NSNotification * _Nullable x) {
        if (self.navigationController.topViewController != self) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
        [self.datasource removeObject:x.object];
        [self.tableView reloadData];
    }];
    
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"pingbiAction" object:nil] subscribeNext:^(NSNotification * _Nullable x) {
        BDHomeModel *model = x.object;
        if (model.is_public == NO) {
            if (self.navigationController.topViewController != self) {
                [self.navigationController popToRootViewControllerAnimated:YES];
            }
            [self.datasource removeObject:x.object];
            [self.tableView reloadData];
        }
    }];

    [[self.cityButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self pushToCityList];
    }];
    [[self.rightButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [BDUserModel judgeCurrentUserWithNormalBlock:^{
            [self pushToPublish];
        }];
    }];
    [[self.searchButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        BDHomeSearchViewController *searchVC = [[BDHomeSearchViewController alloc] init];
        searchVC.hidesBottomBarWhenPushed = YES;
        searchVC.typeString = self.typeString;
        [self.navigationController pushViewController:searchVC animated:YES];
    }];
}

- (void)pushToCityList{
    JFCityViewController *cityViewController = [[JFCityViewController alloc] init];
    cityViewController.title = ASLocalizedString(@"选择城市");
    BDLocationModel *locationModel = [BDLocationModel getLocationInfo];
    [cityViewController setCurrentCityName:locationModel.city];
    __weak typeof(self) weakSelf = self;
    //  你选择城市后的回调，cityName即你选择的城市
    [cityViewController choseCityBlock:^(NSString *cityName) {
        [weakSelf exChangeCityNameWithName:cityName];
        [weakSelf.dictionary removeAllObjects];
        [weakSelf.datasource removeAllObjects];
        weakSelf.startPageArray = @[@"1",@"1",@"1",@"1"].mutableCopy;
        [weakSelf.tableView reloadData];
        [weakSelf requestDatasource];
    }];
    //  给JFCityViewController添加一个导航控制器
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:cityViewController];
    [self presentViewController:navigationController animated:YES completion:nil];
}

- (void)exChangeCityNameWithName:(NSString *)cityName{
//    [[BDLocationServer sharedServer] locatonWithCityName:cityName];
    self.cityButton.titleLabel.font = [UIFont systemFontOfSize:13];
    [self.cityButton setTitle:ASLocalizedString(cityName) forState:UIControlStateNormal];
    CGFloat sizeWidth = [cityName widthWithFont:_cityButton.titleLabel.font];
    self.cityButton.frame = CGRectMake(60, 10, sizeWidth+15, 15);
    [self.cityButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -15, 0, 15)];
    [self.cityButton setImageEdgeInsets:UIEdgeInsetsMake(0, sizeWidth, 0, -sizeWidth)];

    UIBarButtonItem *cityBarButton=[[UIBarButtonItem alloc]initWithCustomView:self.cityButton];
    self.navigationItem.leftBarButtonItem = cityBarButton;
    [[NSUserDefaults standardUserDefaults] setObject:cityName forKey:@"lastCity"];
    [self requestBanner];
}

- (void)pushToPublish{
    BDPublishViewController *publishVC = [[BDPublishViewController alloc] init];
    publishVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:publishVC animated:YES];
}

- (void)requestBanner{
    NSString *lastCity = [[NSUserDefaults standardUserDefaults] objectForKey:@"lastCity"];
    BDCityInfo *cityInfo = [BDCityInfo getCityWithName:lastCity type:BDCityTypeCity];
    NSString *currentCityID = [NSString stringWithFormat:@"%@", @(cityInfo.infoID)];
    
    NSString *url = [NSString stringWithFormat:@"%@banners?position=1&city_id=%@", KBDBaseURL,currentCityID];
    NSString *headValid = [BDUserModel getHeaderValidation];
    
    RACSignal *signal = [[BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
    [signal subscribeNext:^(id  _Nullable x) {
        NSMutableArray *lunboArray = [NSMutableArray array];
        NSArray *arr = x;
        for (int i = 0; i < arr.count; i++) {
            [lunboArray addObject:[arr[i] objectForKey:@"cover"]];
        }
        self.lunboView.imageURLStringsGroup = lunboArray;
        bannerInfos = x;
    }];
    [signal subscribeError:^(NSError * _Nullable error) {
        // BDLog(ASLocalizedString(@"请求广告轮播图失败"));
        [self showErrorViewWithTapBlock:^{
            
        }];
    }];
}

- (void)requestDatasource{
    self.pageSize = @"50";
    // BDLog(ASLocalizedString(@"查询数据库之前"));
    if (isChangeSegementRequest == YES) {
        [self.indicatorView startAnimating];
        self.tableView.hidden = YES;
        isChangeSegementRequest = NO;
    }
    NSString *url = [NSString stringWithFormat:@"%@posts?page=%@&size=%@", KBDBaseURL, self.startPageArray[currentSelectedIndex], self.pageSize];
    NSString *headValid = [BDUserModel getHeaderValidation];

    NSString *lastCity = [[NSUserDefaults standardUserDefaults] objectForKey:@"lastCity"];
    BDCityInfo *cityInfo = [BDCityInfo getCityWithName:lastCity type:BDCityTypeCity];
    NSString *currentCityID = [NSString stringWithFormat:@"%@", @(cityInfo.infoID)];
    
    if ([currentCityID isNotEmpty]) {
        url = [url stringByAppendingString:[NSString stringWithFormat:@"&city_id=%@", currentCityID]];
    }
    
    NSInteger type = 0;
    switch (currentSelectedIndex) {
        //最新
        case 0:
            type = 0;
            break;
        //最近
        case 1:{
            type = 3;
//            BDLocationModel *locationModel = [BDLocationModel getLocationInfo];
            CLLocationCoordinate2D coordinate = [BDLocationServer getLastCoordinate];
            url = [url stringByAppendingString:[NSString stringWithFormat:@"&lng=%f&lat=%f", coordinate.longitude, coordinate.latitude]];
            break;
        }
        //最热
        case 2:
            type = 4;
            break;
        //关注
        case 3:
            type = 6;
            break;
        default:
            break;
    }
    url = [url stringByAppendingString:[NSString stringWithFormat:@"&type=%zd", type]];
    
    url = [url stringByAppendingString:[NSString stringWithFormat:@"&category=%zd", [BDButtonAlert getTypeidWitTypeString:self.typeString]]];
    // BDLog(ASLocalizedString(@"开始获取帖子"));
    //获取帖子列表数据
    RACCommand *command = [BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES];
    RACSignal *signal = [command execute:nil];
    [signal subscribeNext:^(id  _Nullable x) {
        // BDLog(ASLocalizedString(@"获取帖子完成"));
        
//        BDPostListViewController *viewController = [[BDPostListViewController alloc] init];
//        viewController.data = x[@"list"];
//        [self.navigationController pushViewController:viewController animated:YES];
//        return;
        
        self.isEnd = [x[@"is_end"] boolValue];
        self.startPageArray[currentSelectedIndex] = x[@"next_page"];
        NSMutableArray *array = [BDHomeModel mj_objectArrayWithKeyValuesArray:x[@"list"]];
        NSMutableArray *curDa = self.dictionary[[NSString stringWithFormat:@"%zd", currentSelectedIndex]];
        if (curDa == nil) {
            curDa = [NSMutableArray array];
            [self.dictionary setObject:curDa forKey:[NSString stringWithFormat:@"%zd", currentSelectedIndex]];
        }
        [curDa addObjectsFromArray:array];
        self.datasource = curDa;
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [self.datasource removeAllObjects];
            self.startPageArray[currentSelectedIndex] = @"1";
            [self requestDatasource];
        }];
        self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            [self requestDatasource];
        }];
        
        [self setTableiewFooterViewStateFor:self.tableView datasourceCount:self.datasource.count];
        [self.tableView reloadData];
        [self.indicatorView stopAnimating];
        self.tableView.hidden = NO;
        // BDLog(ASLocalizedString(@"刷新页面成功"));
    }];
    
    [signal subscribeError:^(NSError * _Nullable error) {
        [self.indicatorView stopAnimating];
        [self showErrorViewWithTapBlock:^{
            [self requestDatasource];
        }];
    }];
    
    return;
}

#pragma mark ------------------------tableView代理---------------------------
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.datasource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.datasource.count >= indexPath.row + 1) {
        BDHomeModel *model = self.datasource[indexPath.section];
        return model.cellHeight;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BDHomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"shouyeCell" forIndexPath:indexPath];
    if (self.datasource.count >= indexPath.row + 1) {
        __block BDHomeModel *model = self.datasource[indexPath.section];
        model.isDetail = NO;
        [cell configeWithModel:model avatarBlock:^{
            NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
            [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss.SSS"];
            // BDLog(ASLocalizedString(@"点击了头像按钮：%@"), [formatter stringFromDate:[NSDate date]]);
            BDUserInfoViewController *infoVC = [[BDUserInfoViewController alloc] initWithUserID:model.user.user_id isFollow:model.is_follow guanzhuBlock:^(BOOL isFollow) {
                model.is_follow = isFollow;
            }];
            [self.navigationController pushViewController:infoVC animated:YES];
//            NSLog(@"!!!!1%@",self.navigationController);
        } allButtonBlock:^{
            model.isOpen = !model.isOpen;
            [self.tableView reloadData];
        } zanBlock:^(UIButton *button){
            // BDLog(ASLocalizedString(@"点赞按钮"));
            [MBManager showLoadingAlert:ASLocalizedString(@"请稍后")clickHidden:NO clickBlock:nil];
            NSString *url = [NSString stringWithFormat:@"%@post/%@/praise", KBDBaseURL, @(model.my_id)];
            NSDictionary *para = @{@"id":@(model.my_id)};
            NSString *headValid = [BDUserModel getHeaderValidation];
            RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:para validation:headValid automaticProcessingError:YES] execute:nil];
            
            [signal subscribeNext:^(id  _Nullable x) {
                [MBManager hideAlert];
                button.userInteractionEnabled = YES;
                button.selected = !button.selected;
                if (button.isSelected) {
                    model.praiseCount++;
                }else {
                    model.praiseCount--;
                }
                model.praise = button.selected;
                [self.tableView reloadData];
            }];
            [signal subscribeError:^(NSError * _Nullable error) {
//                [MBManager hideAlert];
                button.userInteractionEnabled = YES;
                [MBManager showBriefAlert:ASLocalizedString(@"点赞失败")clickHidden:NO clickBlock:nil];
            }];
        } forwardBlock:^{
            exchangeIndexPath = indexPath;
            BDForwardViewController *forwardVC = [[BDForwardViewController alloc] init];
            forwardVC.homeModel = model;
            forwardVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:forwardVC animated:YES];
        } pinglunBlock:^{
            exchangeIndexPath = indexPath;
            BDHomeDetailViewController *commntVC = [[BDHomeDetailViewController alloc] init];
            commntVC.homeModel = model;
            commntVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:commntVC animated:YES];
        } sharedBlock:^{
            // BDLog(ASLocalizedString(@"分享按钮"));
            //        [UMSocialUIManager setShareMenuViewDelegate:self];
            [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_WechatSession),@(UMSocialPlatformType_WechatTimeLine),@(UMSocialPlatformType_WechatFavorite)]];
            [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
                // 根据获取的platformType确定所选平台进行下一步操作
                NSString *url = [NSString stringWithFormat:@"%@tool/shareData", KBDBaseURL];
                NSString *headValid = [BDUserModel getHeaderValidation];
                RACSignal *signal = [[BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
                
                [signal subscribeNext:^(id  _Nullable x) {
                    //创建分享消息对象
                    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
                    
                    //创建网页内容对象
                    NSString *thumbURL = x[@"share_logo"];
                    NSString *title = x[@"share_title"];
                    NSString *descr = x[@"share_text"];
                    NSString *webUrl = x[@"share_url"];
                    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:title
                                                                                             descr:descr
                                                                                         thumImage:thumbURL];
                    //设置网页地址
                    shareObject.webpageUrl = webUrl;
                    
                    //分享消息对象设置分享内容对象
                    messageObject.shareObject = shareObject;
                    
                    //调用分享接口
                    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
                        if (error) {
                            UMSocialLogInfo(@"************Share fail with error %@*********",error);
                        }else{
                            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                                //                            UMSocialShareResponse *resp = data;
                                //                            //分享结果消息
                                //                            UMSocialLogInfo(@"response message is %@",resp.message);
                                //                            //第三方原始返回的数据
                                //                            UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                                //                            NSLog(ASLocalizedString(@"分享成功了"));
                                NSString *backUrl = [NSString stringWithFormat:@"%@post/%@/shared", KBDBaseURL, @(model.my_id)];
                                RACSignal *backSignal = [[BDNetworkingServer yy_POST:backUrl parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
                                [backSignal subscribeNext:^(id  _Nullable x) {
                                    model.sharedCount++;
                                    [self.tableView reloadData];
                                    [MBManager showBriefAlert:ASLocalizedString(@"分享成功")clickHidden:NO clickBlock:nil];
                                }];
                                [backSignal subscribeError:^(NSError * _Nullable error) {
                                    [MBManager showBriefAlert:ASLocalizedString(@"分享失败")clickHidden:NO clickBlock:nil];
                                }];
                            }else{
                                //                            UMSocialLogInfo(@"response data is %@",data);
                                [MBManager showBriefAlert:ASLocalizedString(@"分享失败")clickHidden:NO clickBlock:nil];
                            }
                        }
                    }];
                }];
                [signal subscribeError:^(NSError * _Nullable error) {
                    [MBManager showBriefAlert:ASLocalizedString(@"获取分享信息失败")clickHidden:NO clickBlock:nil];
                }];
            }];
        } merchantsBlock:^{
            if (model.free || (model.free == NO && model.isPurchase == YES)) {
                BDHomeDetailViewController *detailViewController = [[BDHomeDetailViewController alloc] init];
                detailViewController.hidesBottomBarWhenPushed = YES;
                if (model.haveShopInfo) {
                    detailViewController.homeModel = model;
                }else{
                    detailViewController.homeModel = model.repost;
                }
                [self.navigationController pushViewController:detailViewController animated:YES];
            }else{
                BOOL isControl = [[[NSUserDefaults standardUserDefaults] objectForKey:@"versionControl"] boolValue];
                BDUserModel *currentUser = [BDUserModel getCurrentUser];
                if (isControl == YES || currentUser.is_auth == NO) {
                    [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"购买会员可以查看所有加密帖子，是否前往购买？")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"取消")otherTitle:@[ASLocalizedString(@"好的")] clickBlock:^(NSInteger index) {
                        if (index == 1) {
                            BDVIPViewController *vipVC = [[BDVIPViewController alloc] init];
                            vipVC.hidesBottomBarWhenPushed = YES;
                            [self.navigationController pushViewController:vipVC animated:YES];
                        }
                    }];
                }else{
                    BDPayViewController *payVC = [[BDPayViewController alloc] initWithPaySuccessedBlock:^{
                        [MBManager showBriefAlert:ASLocalizedString(@"支付成功")clickHidden:NO clickBlock:nil];
                        model.purchase = @[@""];
                        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                    }];
                    payVC.productId = [NSString stringWithFormat:@"%@", @(model.my_id)];
                    payVC.price = [NSDecimalNumber decimalNumberWithDecimal:[@(model.price) decimalValue]];
                    payVC.payType = BDPayTypePost;
                    payVC.product = model;
                    payVC.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:payVC animated:YES];
                }
            }
        } imageClickBlock:^(NSInteger index, NSArray *imagesArray, UIView *clickView) {
            showImagesArray = imagesArray;
            PBViewController *pbViewController = [PBViewController new];
            pbViewController.pb_dataSource = self;
            pbViewController.pb_delegate = self;
            pbViewController.pb_startPage = index;
            curClickView = clickView;
            [self presentViewController:pbViewController animated:YES completion:nil];
        }];
    }
    return cell;
}


#pragma mark ------------------------PBViewController代理---------------------------
- (NSInteger)numberOfPagesInViewController:(PBViewController *)viewController {
    return showImagesArray.count;
}

- (void)viewController:(PBViewController *)viewController presentImageView:(UIImageView *)imageView forPageAtIndex:(NSInteger)index progressHandler:(void (^)(NSInteger, NSInteger))progressHandler {
    
    UIImage *placeholder = [UIImage imageNamed:@"business_pic"];
    [imageView sd_setImageWithURL:[NSURL URLWithString:showImagesArray[index]]
                 placeholderImage:placeholder
                          options:0
                         progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
                             
                         } completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                             
                         }];
}

- (UIView *)thumbViewForPageAtIndex:(NSInteger)index {
    return curClickView;
}

- (void)viewController:(PBViewController *)viewController didSingleTapedPageAtIndex:(NSInteger)index presentedImage:(UIImage *)presentedImage {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark ------------------------scrollView代理---------------------------
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if ([scrollView isKindOfClass:[UITableView class]]) {
        CGFloat offset = scrollView.contentOffset.y + self.topView.height;
//        // BDLog(ASLocalizedString(@"当前偏移量:%.2f"), offset);
        CGFloat newBottom = self.topView.height + kBDTopHeight - offset;
        newBottom = newBottom < kBDTopHeight + 40 ? kBDTopHeight + 40 : newBottom;
        newBottom = newBottom > self.topView.height + kBDTopHeight ? self.topView.height + kBDTopHeight : newBottom;
        self.topView.bottom = newBottom;
        self.indicatorView.top = self.topView.bottom;
    }
}

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    NSDictionary *bannerInfo = bannerInfos[index];
    NSInteger shopId = [bannerInfo[@"shop_id"] integerValue];
    if (shopId) {
        BDShopInfoDeatilViewController *shopInfoVC = [[BDShopInfoDeatilViewController alloc] init];
        shopInfoVC.shopID = [NSString stringWithFormat:@"%zd", shopId];
        shopInfoVC.title = bannerInfo[@"title"];
        [self.navigationController pushViewController:shopInfoVC animated:YES];
    }
}

#pragma mark ------------------------懒加载---------------------------
- (UIButton *)cityButton{
    if (!_cityButton) {
        self.cityButton = [[UIButton alloc] init];
        _cityButton.titleLabel.font = [UIFont systemFontOfSize:13];
        NSString *lastCity = [[NSUserDefaults standardUserDefaults] objectForKey:@"lastCity"];
        NSString *title = [lastCity isNotEmpty] ? lastCity : ASLocalizedString(@"选择城市");
        CGFloat sizeWidth = [title widthWithFont:_cityButton.titleLabel.font];
        [_cityButton setTitle:ASLocalizedString(title) forState:UIControlStateNormal];
        _cityButton.frame = CGRectMake(60, 10, sizeWidth+15, 15);
        [_cityButton setImage:[UIImage imageNamed:@"xia"] forState:UIControlStateNormal];
        [_cityButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_cityButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -15, 0, 15)];
        [_cityButton setImageEdgeInsets:UIEdgeInsetsMake(0, sizeWidth, 0, -sizeWidth)];
    }
    return _cityButton;
}

- (UIButton *)rightButton{
    if (!_rightButton) {
        self.rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30 ,30)];
        [_rightButton setImage:[UIImage imageNamed:@"fabiao"] forState:UIControlStateNormal];
    }
    return _rightButton;
}

- (UIButton *)searchButton{
    if (!_searchButton) {
        self.searchButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 35 ,30)];
        [_searchButton setImage:[UIImage imageNamed:@"item_sousuo"] forState:UIControlStateNormal];
    }
    return _searchButton;
}

- (UITableView *)tableView{
    if (!_tableView) {
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTopHeight - kBDTabBarHeight) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
//        _tableView.tableHeaderView = [self customTableHeaderView];
        _tableView.contentInset = UIEdgeInsetsMake(self.topView.height, 0, 0, 0);
        _tableView.separatorColor = [UIColor clearColor];
        _tableView.sectionHeaderHeight = 0;
        _tableView.sectionFooterHeight = 10;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 0.1)];
        [_tableView registerClass:[BDHomeTableViewCell class] forCellReuseIdentifier:@"shouyeCell"];
    }
    return _tableView;
}

- (NSMutableDictionary *)dictionary{
    if (!_dictionary) {
        self.dictionary = [NSMutableDictionary dictionary];
    }
    return _dictionary;
}

- (SDCycleScrollView *)lunboView{
    if (!_lunboView) {
        self.lunboView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kBDScreenWidth, 100 / 375.0 * kBDScreenWidth) delegate:self placeholderImage:[UIImage imageNamed:@"shop_pic"]];
    }
    return _lunboView;
}

- (UIView *)topView{
    if (!_topView) {
        self.topView = [[UIView alloc] initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, 100 / 375.0 * kBDScreenWidth + 45)];
        [_topView addSubview:self.lunboView];
        
        UIView *head = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 45)];
        head.backgroundColor = kBDColorGray;
        head.bottom = _topView.height;
        [_topView addSubview:head];
        
        UIView *contenView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 40)];
        contenView.backgroundColor = [UIColor whiteColor];
        [head addSubview:contenView];
        
        NSArray *buttArr = @[ASLocalizedString(@"最新发表"),ASLocalizedString(@"离我最近"),ASLocalizedString(@"最热主题"), ASLocalizedString(@"我的关注")];
        CGFloat buttonWidth = 70;
        CGFloat space = (kBDScreenWidth - buttonWidth * buttArr.count) / (buttArr.count + 1);
        
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(space, 0, buttonWidth, 1.5)];
        lineView.backgroundColor = KBDColorBlue;
        lineView.bottom = contenView.height;
        [contenView addSubview:lineView];
        
        for (int i = 0; i < buttArr.count; i++) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(space + (space + buttonWidth)*i, 0, buttonWidth, 40);
            [button setTitle:buttArr[i] forState:UIControlStateNormal];
            [button setTitleColor:[UIColor colorWithHexString:@"#1c1c1c"] forState:UIControlStateNormal];
            [button setTitleColor:KBDColorBlue forState:UIControlStateSelected];
            button.titleLabel.font = [UIFont systemFontOfSize:14];
            button.tag = 1415 + i;
            [contenView addSubview:button];
            if (i == 0) {
                button.selected = YES;
                currentSelectedIndex = i;
            }
            [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                if ( i == currentSelectedIndex) {
                    // BDLog(ASLocalizedString(@"点击了相同的按钮"));
                    return;
                }
                UIButton *oldButton = [contenView viewWithTag:1415 + currentSelectedIndex];
                oldButton.selected  = NO;
                
                [UIView animateWithDuration:0.3 animations:^{
                    lineView.centerX = button.centerX;
                } completion:^(BOOL finished) {
                    button.selected = YES;
                    currentSelectedIndex = i;
                    NSMutableArray *curDa = self.dictionary[[NSString stringWithFormat:@"%zd", currentSelectedIndex]];
                    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
                        [self.datasource removeAllObjects];
                        self.startPageArray[currentSelectedIndex] = @"1";
                        [self requestDatasource];
                    }];
                    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                        [self requestDatasource];
                    }];
                    if (curDa.count == 0) {
                        isChangeSegementRequest = YES;
                        [self requestDatasource];
                    }else{
                        self.datasource = curDa;
                        [self.tableView reloadData];
                        [self setTableiewFooterViewStateFor:self.tableView datasourceCount:self.datasource.count];
                    }
                }];
            }];
        }
    }
    return _topView;
}

- (UIActivityIndicatorView *)indicatorView{
    if (!_indicatorView) {
        self.indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _indicatorView.hidesWhenStopped = YES;
        _indicatorView.frame = CGRectMake(0, self.topView.bottom, kBDScreenWidth, 50);
        [self.view addSubview:_indicatorView];
    }
    return _indicatorView;
}

- (NSMutableArray *)datasource{
    if (!_datasource) {
        self.datasource = [NSMutableArray array];
    }
    return _datasource;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
